// pages/dashboard/ecgScan/ecgScan.js
const util = require('../../../utils/util.js')

function inArray(arr, key ,val){
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i
        }
    }
    return -1
}

var appInstance = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        list:[{
            name:'ECGRec_202020/C800001',
        },{
            name:"ECGRec_202020/C800002",
        },{
            name:"ECGRec_202020/C800003",
        },{
            name:"ECGRec_202020/C800004",
        },{
            name:"ECGRec_202020/C800005",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        },{
            name:"ECGRec_202020/C800006",
        }],
        devices:[],
        scanType: "ecg",
    },
    openAdapter(){
        appInstance.openBleAdapter((response) =>{
            console.log('adapter:',response)
            if (response.errMsg == "openBluetoothAdapter:ok" || response.errMsg == "openBluetoothAdapter:fail already opened") {
                this.startScanECG()
            }
        })        
    },
    closeAdapter(){
        appInstance.closeBleAdapter({

        })       
    },
    startScanECG(){
        appInstance.startScan((response) => {
            var msg = response['errMsg']
            if (msg == 'startBluetoothDevicesDiscovery:fail 请先调用 wx.openBluetoothAdapter 接口进行初始化操作'){
                msg = 'not open Adapter'
                wx.showToast({
                    title: msg,
                })
            }
            console.log('获取到回调内容:',response)
            if (msg == 'startBluetoothDevicesDiscovery:ok') {
                this.onBluetoothDeviceFound()
            }
        })
    },
    onBluetoothDeviceFound(){
        var that = this
        console.log('onBluetoothDeviceFound')
        wx.onBluetoothDeviceFound((res) => {
            res.devices.forEach(device => {
                // console.log(device)
                if (!device.name && !device.localName) {
                    return
                }
                if (that.data.scanType == 'ecg') {
                    if (device.name.indexOf('ECGRec') < 0) {
                        return
                    }
                    if (device.name.length != 21 || device.localName.length != 21) {
                        return
                    }
                }else if (that.data.scanType == 'spo2') {
                    if (device.name.indexOf('O2') < 0) {
                        return
                    }
                }else if (that.data.scanType == 'bp') {
                    if (device.name.indexOf('BP5') < 0) {
                        return
                    }
                    //将广告数据中的MAC地址取出
                    let manufacturerDataStr = util.arrayToHexString(device.advertisData)
                    let macStr = manufacturerDataStr.substring(manufacturerDataStr.length - 12)
                    let adverName = device.name.substring(0,4) +' '+ macStr.toLocaleUpperCase()
                    device.name = adverName
                }else{
                    return
                }
                
                const foundDevices = this.data.devices
                const idx = inArray(foundDevices, 'deviceId', device.deviceId)
                const data = {}
                if (idx === -1) {
                    data[`devices[${foundDevices.length}]`] = device
                } else {
                    // data[`devices[${idx}]`] = device
                    return
                }
                this.setData(data)
            })
          })
    },

    troubleShoot(){
        console.log("trouble shoot")
    },
    
    connectSuccess(e){
        this.stopScanECG()
        const ds = e.currentTarget.dataset
        const deviceId = ds.deviceId
        const name = ds.name
        console.log('连接的设备id ',deviceId)
        console.log('连接的设备名 ', name)
        wx.showLoading({
            title: 'connecting '+name,
        })
        appInstance.globalData.deviceId = deviceId
        appInstance.connectSensor(deviceId,30*1000,(response) =>{
            console.log(response)
            wx.hideLoading({
                success: (res) => {},
            })
            if (response == '连接成功') {
                this.setData({
                    devices: [],
                })
                // let batteryValue = appInstance.globalData.ecg.battery
                appInstance.globalData.ecg = {connected:true,battery:"100",deviceName:name}
                setTimeout(function() {
                    wx.reLaunch({
                        url: '../../dashboard/dashboard',
                    })
                },2000)
            }else {
                wx.showToast({
                    title: response,
                })
            }
        })

        wx.onBLECharacteristicValueChange((characteristic) => {
            // console.log('收到特征uuid:',characteristic.characteristicId)
            // console.log('收到的ori数据:',characteristic.value)
            console.log('收到的数据:',util.arrayToHexString(characteristic.value))
            var byteArray = new Uint8Array(characteristic.value)
            var valueStr = util.arrayToHexString(characteristic.value)
            var data_type = ''
            if (characteristic.characteristicId == '00002A29-0000-1000-8000-00805F9B34FB') {
                //设备信息
                data_type = '设备信息'
                valueStr = util.utf8ByteToUnicodeStr(byteArray)
            }else if (characteristic.characteristicId == '00002A27-0000-1000-8000-00805F9B34FB') {
                data_type = '硬件版本号'
                valueStr = util.utf8ByteToUnicodeStr(byteArray)
                appInstance.globalData.hw = valueStr
                let keyStr = name.replace('ECGRec_', '') + valueStr
                console.log("硬件版本号:",keyStr)
                appInstance.globalData.decryptKey = keyStr
            }else if (characteristic.characteristicId == '00002A26-0000-1000-8000-00805F9B34FB') {
                data_type = '固件版本号'
                valueStr = util.utf8ByteToUnicodeStr(byteArray)
                appInstance.globalData.fw = valueStr
            }
        })
        
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log('Scan onLoad ',options.type)
        this.setData({
            scanType:options.type,
        })
        //打开蓝牙适配器
        this.openAdapter()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.startScanECG()
    },
    stopScanECG(){
        appInstance.stopScan((response) =>{
            // console.log(response)
        })
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})